#include "RGBPcm2Mp4Controller.h"

#include <QDebug>


RGBPcm2Mp4Controller::RGBPcm2Mp4Controller()
{
}

void RGBPcm2Mp4Controller::run()
{
	RGBPcm2Mp4Writer* xw = RGBPcm2Mp4Writer::Get(0);


	qDebug() << xw->Init(outMp4FilePath);
	qDebug() << xw->AddVideoStream();
	xw->AddAudioStream();

	FILE* fp = fopen(inputRGBFilePath.toStdString().c_str(), "rb");
	if (!fp)
	{
		qDebug() << "open " << inputRGBFilePath.toStdString().c_str() << " failed!";
		return;
	}
	FILE* fa = fopen(inputPCMFilePath.toStdString().c_str(), "rb");
	if (!fa)
	{
		qDebug() << "open " << inputPCMFilePath.toStdString().c_str() << " failed!";
		return;
	}

	int size = xw->inWidth * xw->inHeight * 4;
	unsigned char* rgb = new unsigned char[size];

	int asize = xw->nb_sample * xw->inChannels * 2;
	unsigned char* pcm = new unsigned char[asize];

	xw->WriteHead();
	AVPacket* pkt = NULL;
	int len = 0;
	for (;;)
	{
		if (xw->IsVideoBefor())
		{
			len = fread(rgb, 1, size, fp);
			if (len <= 0)
				break;
			pkt = xw->EncodeVideo(rgb);
			if (pkt) qDebug() << ".";
			else
			{
				qDebug() << "-";
				continue;
			}

			if (xw->WriteFrame(pkt))
			{
				qDebug() << "+";
			}
		}
		else
		{
			len = fread(pcm, 1, asize, fa);
			if (len <= 0)break;
			pkt = xw->EncodeAudio(pcm);
			xw->WriteFrame(pkt);
		}

	}
	xw->WriteEnd();
	delete rgb;
	rgb = NULL;
	qDebug() << "\n============================end============================" << endl;
}
void RGBPcm2Mp4Controller::Start()
{
	qDebug() << "开启一个线生成mp4";
	this->start();
}


RGBPcm2Mp4Controller::~RGBPcm2Mp4Controller()
{
}
